<template>
    <!--投稿视频页面-->
  <a-flex vertical gap="middle"  justify="center" align="left" style="margin: 30px">
    <div style="margin: 5px">
      <a-row justify="space-around" align="middle">
        <a-col :span="2">
          <span v-if="videoPublishProps.url === ''" style="font-size: 16px;color: red;width: 12px">*</span>
          <span style="font-size: 16px;font-weight: 600;color: black">上传视频: </span>
        </a-col>
        <a-col :span="18">
          <SingleUpload @get-instance="getInstanceFromSingleUpload" :option="uploadOption"/>
        </a-col>
      </a-row>
    </div>
    <div style="margin: 5px">
      <a-row>
        <a-col :span="1">
          <span v-if="videoPublishProps.title === ''" style="font-size: 16px;color: red;width: 12px">*</span>
          <span style="font-size: 16px;font-weight: 600;color: black">标题: </span>
        </a-col>
        <a-col :span="18">
          <a-input v-model:value="videoPublishProps.title" placeholder="取一个吸引人的标题吧" />
        </a-col>
      </a-row>
    </div>
    <div style="margin: 5px">
      <a-row>
        <a-col :span="1">
          <span v-if="videoPublishProps.catId === ''" style="font-size: 16px;color: red;width: 12px">*</span>
          <span style="font-size: 16px;font-weight: 600;color: black">分类: </span>
        </a-col>
        <a-col :span="18">
          <a-tree-select
              v-model:value="categoryVal"
              v-model:searchValue="categorySearchValue"
              show-search
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="选择一个合理的分类吧，支持搜索哦！"
              allow-clear
              tree-default-expand-all
              :tree-data="videoCategoryData"
              tree-node-filter-prop="label"
          >
            <template #title="{ value: val, label }">
              <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
              <template v-else>
                <template
                    v-for="(fragment, i) in label
                              .toString()
                              .split(new RegExp(`(?<=${categorySearchValue})|(?=${categorySearchValue})`, 'i'))">
                            <span
                                v-if="fragment.toLowerCase() === categorySearchValue.toLowerCase()"
                                :key="i"
                                style="color: #08c"
                            >
                              {{ fragment }}
                            </span>
                  <template v-else>{{ fragment }}</template>
                </template>
              </template>
            </template>
          </a-tree-select>
        </a-col>
      </a-row>
    </div>
    <div style="margin: 5px">
      <a-row>
        <a-col :span="1">
          <span style="font-size: 16px;font-weight: 600;color: black">简介: </span>
        </a-col>
        <a-col :span="18">
          <a-textarea
              v-model:value="videoPublishProps.introduce"
              placeholder="做个简短的介绍！"
              :rows="4"
          />
        </a-col>
      </a-row>
    </div>
    <div style="margin: 5px">
      <a-row>
        <a-col :span="1">
          <span v-if="videoPublishProps.coverPicture === ''" style="font-size: 16px;color: red;width: 12px">*</span>
          <span style="font-size: 16px;font-weight: 600;color: black">封面: </span>
        </a-col>
        <a-col :span="18">
          <upload-single-img @get-instance="getInstanceFromUploadImg"/>
        </a-col>
      </a-row>
    </div>
    <div style="margin: 5px">
      <a-space :size="12">
        <a-button type="dashed" shape="round" size="large" @click="saveTemp">
          暂存草稿
        </a-button>
        <a-button type="primary" shape="round" size="large" @click="visiblePublishModal">
          立即投稿
        </a-button>
        <a-modal v-model:open="publishModalVisible" title="立即投稿" @ok="handlePublishModalOk">
          <template #footer>
            <a-button key="back" @click="()=>{publishModalVisible=false}">返回</a-button>
            <a-button :disabled="publishButtonDisable" key="submit" type="primary" :loading="loading" @click="handlePublishModalOk">提交</a-button>
          </template>
          <a-space size="small">
            <a-alert v-if="videoPublishProps.catId === ''" message="请选择分类" type="error" />
            <a-alert v-if="videoPublishProps.url === ''||videoPublishProps.md5 === '' || videoPublishProps.format===''||videoPublishProps.size===0||videoPublishProps.duration===0"
                     message="请上传视频" type="error" />
            <a-alert v-if="videoPublishProps.title === ''" message="请填写标题" type="error" />
            <a-alert v-if="videoPublishProps.coverPicture === ''" message="请上传封面" type="error" />
            <p v-if="publishButtonDisable===false"> <ExclamationCircleOutlined/> 要素齐全！</p>
          </a-space>
        </a-modal>
      </a-space>
    </div>
  </a-flex>
</template>

<script setup>
import SingleUpload from "@/components/common/SingleUpload.vue";
import UploadSingleImg from "@/components/common/UploadSingleImg.vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";
import {ref, reactive, watch, onBeforeMount} from "vue";
import {getVideoDuration} from "@/utils/FileUtils.js";
import {listCategoryTree, publishVideo} from "@/api/VideoRequest.js";
import {message} from "ant-design-vue";
import router from "@/router/index.js";

const categoryVal = ref();
const publishModalVisible = ref(false);
const publishButtonDisable = ref(true);
const loading = ref(false);
const uploadOption = ref({
  areaTitle: '点击或拖拽mp4格式视频文件以上传',
  fileType: 'video/mp4'
});
const videoCategoryData = ref([])
const categorySearchValue = ref('');
/** 视频投稿参数 */
const videoPublishProps = reactive({});

watch(categoryVal, () => {
  videoPublishProps.catId = categoryVal.value;
});

watch(videoPublishProps, (val) => {
  publishButtonDisable.value = !(val.catId !== '' && val.md5 !== '' && val.title !== '' && val.url !== '' && val.format !== '' && val.size > 0 && val.duration > 0 && val.coverPicture !== '');
});

function initVideoPublishProps() {
  videoPublishProps.catId = '';
  videoPublishProps.md5 = '';
  videoPublishProps.title = '';
  videoPublishProps.introduce = '';
  videoPublishProps.format = '';
  videoPublishProps.url = '';
  videoPublishProps.coverPicture = '';
  videoPublishProps.size = 0;
  videoPublishProps.duration = 0;
}

function initVideo() {
  videoPublishProps.url = '';
  videoPublishProps.md5 = '';
  videoPublishProps.format = '';
  videoPublishProps.size = 0;
  videoPublishProps.duration = 0;
}

async function getInstanceFromSingleUpload(instance) {
  console.log('从上传视频组件里获取的对象',instance);
  if (typeof instance.err !== 'undefined' || typeof instance.remove !== 'undefined') {
    initVideo();
  }

  if(typeof instance.success !== 'undefined') {
    videoPublishProps.duration = await getVideoDuration(instance.file);
    videoPublishProps.format = instance.file.name.split('.')[1]
    videoPublishProps.md5 = instance.md5;
    videoPublishProps.url = instance.bucketName + ':' + instance.objectName;
    videoPublishProps.size = instance.file.size;
  }
}

function getInstanceFromUploadImg(instance) {
  videoPublishProps.coverPicture = instance.bucketName + ':' + instance.objectName;
  if(typeof instance.remove !== 'undefined') {
    videoPublishProps.coverPicture = '';
  }
}

function saveTemp() {
  console.log('暂存视频投稿参数',videoPublishProps);
}

function visiblePublishModal() {
  publishModalVisible.value = true;
}

/**
 * 点击确定按钮，直接发布视频
 * @returns {Promise<void>}
 */
async function handlePublishModalOk() {
  console.log('点击确定按钮', videoPublishProps);
  loading.value = true;
  const res = await publishVideo(videoPublishProps.catId, videoPublishProps.md5,
      videoPublishProps.title,videoPublishProps.introduce,
      videoPublishProps.format, videoPublishProps.url,
      videoPublishProps.coverPicture, videoPublishProps.size, videoPublishProps.duration);
  console.log('发布视频返回结果', res);
  if(res.code === 0) {
    // TODO 跳转到稿件管理
    await router.push('/upload-manager/manager-video')
  } else {
    message.warn(`发布视频失败：${res.msg}`);
  }
  loading.value = false;
  publishModalVisible.value = false;
}

onBeforeMount(_=> {
  initVideoPublishProps();

  listCategoryTree().then(res => {
    if(res.code === 0){
      videoCategoryData.value = res.data;
    } else {
      message.error(res.msg);
    }
  });
})

</script>

<style scoped>

</style>